package com.blacktea.behavioralpatterns.mementopattern;

import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @description: 购物车类
 * @author: black tea
 * @date: 2023/3/25 20:12
 */
@Component
public class Cart {

    /**
     * 商品列表
     */
    private List<Goods> items = new ArrayList<>();
    /**
     * 总价
     */
    private BigDecimal totalPrice = BigDecimal.ZERO;

    /**
     * 添加商品
     * @param goods 商品
     */
    public void addItem(Goods goods) {
        items.add(goods);
        totalPrice = totalPrice.add(goods.getPrice());
    }

    /**
     * 创建备忘录对象
     * @return CartMemento 备忘录对象
     */
    public CartMemento createMemento() {
        return new CartMemento(new ArrayList<>(items), totalPrice);
    }

    /**
     * 恢复状态
     *
     * @param memento 备忘录对象
     */
    public void restoreMemento(CartMemento memento) {
        items = new ArrayList<>(memento.getItems());
        totalPrice = memento.getTotalPrice();
    }

    public List<Goods> getItems() {
        return items;
    }

    public BigDecimal getTotalPrice() {
        return totalPrice;
    }
}
